package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.dto.UpdateArticleMessage;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.service.ILikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LikesBehaviorServiceImpl implements ILikesBehaviorService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired(required = false)
    KafkaTemplate<String,String> kafkaTemplate;
    //点赞
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //构建ApLikeBehavior
        ApLikesBehavior likesBehavior = new ApLikesBehavior();
        likesBehavior.setArticleId(dto.getArticleId());
        likesBehavior.setType(dto.getType());
        likesBehavior.setOperation(dto.getOperation());
        likesBehavior.setCreatedTime(new Date());
        //判断用户是登录还是游客
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        User user = AppThreadLocalUtil.get();
        if (user != null) {
            likesBehavior.setUserId(user.getUserId());
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        } else {
            likesBehavior.setEquipmentId(dto.getEquipmentId());
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        //查询是否有记录
        ApLikesBehavior one = mongoTemplate.findOne(query, ApLikesBehavior.class);
        if (one == null) {
            //没有记录，新增
            if (dto.getOperation() == 0) {
                mongoTemplate.save(likesBehavior);
                //发送消息到kafka
                sendMessage(dto.getArticleId(), 1,1);
            }
        } else {
            //有记录，更新,如果数据库中操作类型和当前操作类型不一致，才更新
            if (one.getOperation() != dto.getOperation()) {
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                int add = 1;
                if (dto.getOperation() == 1) {
                    add = -1;
                }
                //发送消息到kafka
                sendMessage(dto.getArticleId(), add,1);
            }
        }
        return ResponseResult.okResult();
    }

    //查询点赞
    @Override
    public ResponseResult<ApLikesBehavior> getLikes(LikesBehaviorDto dto) {
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (dto.getUserId() != null) {
            query.addCriteria(Criteria.where("userId").is(dto.getUserId()));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        query.addCriteria(Criteria.where("operation").is(0));
        //查询是否有记录
        ApLikesBehavior one = mongoTemplate.findOne(query, ApLikesBehavior.class);
        return ResponseResult.okResult(one);
    }

    /**
     * 发送消息到kafka
     * @param articleId
     * @param add
     */
    private void sendMessage(Long articleId, int add,int type) {
        UpdateArticleMessage message = new UpdateArticleMessage();
        message.setArticleId(articleId);
        message.setType(type);
        message.setAdd(add);
        String data = JSON.toJSONString(message);
        kafkaTemplate.send(articleBehaviorTopic, data);
    }

    @Value("${topic.articleBehaviorTopic}")
    private String articleBehaviorTopic;
}
